<template>
  <div class="root">
    <!-- 角色设置 -->
    <div class="left-part">
      <p>角色设置</p>
      <div class="role-title">
        <template v-for="(item, index) in roles">
          <p
            :key="index"
            :class="item.isCheck ? 'p-checked' : 'p-notcheck'"
            @click="checkFn(index, 'roles')"
          >
            {{ item.title }}
          </p>
        </template>
      </div>
      <div class="btn-group">
        <template v-for="(item, index) in btns">
          <Button
            :key="index"
            style=""
            :type="item.isCheck ? 'primary' : 'default'"
            @click="checkFn(index, 'btns')"
          >
            {{ item.title }}
          </Button>
        </template>
      </div>
      <div style="width:100%;margin:10px  auto">
        <template v-for="(item, index) in pList">
          <div :key="index" class="role-p" @click="chooseRole(item.id)">
            <p v-if="!item.editStatus">{{ item.name }} ({{ item.userCount }}人)</p>
            <Input v-else v-model="item.name" @on-blur="editNameBlur(item.id,item.name)"></Input>
            <p><span @click.stop="editRoleName(item.id)" v-show ="!item.editStatus">编辑</span><span @click.stop="delRoleName(item.id)">删除</span></p>
          </div>
        </template>
        <Input v-if="addStatus" placeholder="请添加角色" style="height:40px!important" v-model="roleName" @on-blur="addBlur"></Input>
      </div>
    </div>
    <!-- 右侧详细设置 -->
    <div class="right-part">
      <div class="right-content">
        <p class="role">{{role}}</p>
        <div class="promission-title">
          <template v-for="(item, index) in promissionL">
            <p
              :key="index"
              :class="item.isCheck ? 'p-checked' : 'p-notcheck'"
              @click="checkFn(index, 'promissionL')"
            >
              {{ item.title }}
            </p>
          </template>
        </div>
        <div style="clear:both">
          <template v-if="rightTab == 1">
            <Button type="primary" style="float: right; margin-top: -50px;" @click="saveRolePermissPre">保存</Button>
              <div
                style="padding-bottom:6px;margin-bottom:6px;"
              >
                <div class="checkoutBox">
                   <Checkbox value="全选" v-model="checkAll" @on-change="handleCheckAll">全选</Checkbox>
                    <!-- <input type="checkbox" value="全选" :checked="checkAll" @change="handleCheckAll"><span>全选</span> -->
                </div>
                <div v-for="(item,index) in promisCheckList" :key="index">
                  <Checkbox :value="item.nodeName" v-model="item.checked"  @on-change="pCheckChange($event,item.nodeId)">{{item.nodeName}}</Checkbox>
                  <div class="checkoutBox child" v-for="(citem,cindex) in item.children" :key="cindex">
                    <Checkbox :value="citem.nodeName" v-model="citem.checked" @on-change="cCheckChange($event,citem.nodeId,index)">{{citem.nodeName}}</Checkbox>
                    <br />
                    <div class="checkoutBox child perm-box" v-for="(permItem,permIndex) in citem.children" :key="permIndex">
                      <Checkbox :value="permItem.nodeName" v-model="permItem.checked" @on-change="permCheckChange($event,permItem.nodeId,index,cindex)">{{permItem.nodeName}}</Checkbox>
                    </div>
                  </div>
                </div>
                <!-- <div v-for="(item,index) in promisCheckList" :key="index">
                    <div class="checkoutBox">
                     <input type="checkbox" :value="item.nodeName" :checked="item.checked" @change="pCheckChange($event,item.nodeId)"> <span>{{item.nodeName}}</span>
                    </div>
                    <div class="checkoutBox child" v-for="(citem,cindex) in item.children" :key="cindex">
                       <input type="checkbox" :value="citem.nodeName" :checked="citem.checked" @change="cCheckChange($event,citem.nodeId,index)"><span>{{citem.nodeName}}</span>
                    </div>
                </div> -->
              </div>
          </template>
          <template v-if="rightTab == 2">
            <Table border :columns="tableCol" :data="roleTableList" :loading="tableLoading" stripe  ref="roleTableList">
              <template slot="action" slot-scope="{ row}">
                <Button
                  @click="handleRoleEditClick(row.userid,'look')"
                  size="small"
                  style="margin-right: 5px"
                  type="primary"
                >查看</Button>
                <Button
                  @click="handleRoleEditClick(row.userid,'edit')"
                  size="small"
                  style="margin-right: 5px"
                  type="primary"
                >编辑</Button>
                <Button @click="handleRoleDeleteClick(row.userid)" size="small" type="error">删除</Button>
              </template>
            </Table>
            <div class="page-wrapper clearfix pageBox" >
              <Page
                :current="page"
                :total="total"
                :page-size="10"
                @on-change="handlePageChange"
                @on-page-size-change="handlePageSizeChange"
                show-sizer
                show-total
                style="position:absolute;right:0px"
              />
            </div>
          </template>
        </div>
      </div>
    </div>
     <ModalStaff
      :isEdit="modalStaffIsEdit"
      :oprStaffId="oprStaffId"
      :selectTreeNode="selectTreeNode"
      :title ="modelTitle"
      @on-save-success="handleStaffSave"
      v-model="editStaffVisiable"
    />
  </div>
</template>
<script>
import CountTo from '_c/count-to';
import ModalStaff from '../staff/modal-staff';

import {
  getRoleList,
  addRole,
  delRole,
  editRoleName,
  getPermissByRoleId,
  getUserByRoleId,
  saveRolePermiss
} from '@/api/roles.js';

import {
  delUser
} from '@/api/staff.js';

export default {
  name: 'count_to_page',
  components: {
    CountTo,
    ModalStaff
  },

  data () {
    return {
      roles: [
        { title: '功能角色', isCheck: true }
        // { title: '数据角色', isCheck: false }
      ],
      btns: [
        { title: '添加角色', isCheck: true }
        // { title: '复制角色', isCheck: false }
      ],
      promissionL: [
        { title: '权限设置', isCheck: true },
        { title: '所属人员', isCheck: false }
        // { title: '按钮权限', isCheck: false }
      ],
      pList: [],
      dList: [
        { name: '超级管理员' },
        { name: '普通管理员' },
        { name: '普通用户' }
      ],
      promisCheckList: [], // 权限设置的选择框
      checkAll: false, // 权限是否为全选
      addStatus: false, // 是否添加角色
      roleName: '', // 添加的角色名称
      role: '', // 右侧边展示得角色
      rightTab: 1, // 右边默认显示的权限设置
      tableCol: [
        { title: '姓名', key: 'fullname' },
        { title: '账号', key: 'acc' },
        { title: '公司', key: 'company' },
        { title: '部门', key: 'dept' },
        { title: '角色', key: 'role' },
        { title: '岗位', key: 'job' },
        { title: '操作', slot: 'action', width: 180 }
      ],
      roleTableList: [], // 角色所属人员
      total: 0,
      page: 1,
      pageSize: 10,
      tableLoading: true,
      roleId: '', // 当前选择的角色id

      // 添加编辑员工弹窗
      editStaffVisiable: false,
      modalStaffIsEdit: false,
      oprStaffId: '',
      selectTreeNode: {},
      modelTitle: '添加员工'
    };
  },
  mounted () {
    this.getRoleList();
  },
  methods: {
    // 获取角色列表，加参数表示，删除员工后重新获取
    async getRoleList (type) {
      const resp = await getRoleList();
      if (resp.data.msg == 'success') {
        this.pList = resp.data.data;
      }
      let data = resp.data.data;
      if (data.length > 0) {
        if (type) {
          this.pList.forEach((item, index) => {
            if (item.id == this.roleId) {
              this.role = item.name + '(' + item.userCount + '人)';
            }
          });
        } else {
          this.roleId = data[0].id;
          this.role = data[0].name + '(' + data[0].userCount + '人)';
          this.pList.forEach((item, index) => {
            this.$set(item, 'editStatus', false);
          });
          this.getPermissByRoleId();
        }
      }
    },
    async getPermissByRoleId () {
      this.tableLoading = true;
      const resp = await getPermissByRoleId(this.roleId);
      console.log(resp, '456465654');
      const { msg, data } = resp.data;
      if (msg == 'success') {
        data.forEach((item, index) => {
          if (item.checked) {
            this.checkAll = true;
          }
          this.promisCheckList = item.children;
        });
        this.checkAllcheckbox();
      }
      // console.log(resp, '权限列表');
    },
    async getUserByRoleId () {
      this.tableLoading = true;
      const data = {
        id: this.roleId,
        pageSize: this.pageSize,
        pageNum: this.page
      };
      const resp = await getUserByRoleId(data);
      this.tableLoading = false;
      this.total = resp.data.total;
      this.roleTableList = resp.data.data;
      // console.log(resp, '所属人员');
    },
    saveRolePermissPre () {
      this.checkedIds = '';
      this.promisCheckList.forEach((item, index) => {
        if (item.checked) {
          if (this.checkedIds != '') {
            this.checkedIds = this.checkedIds + ',' + item.nodeId;
          } else {
            this.checkedIds = this.checkedIds + item.nodeId;
          }
        }
        item.children.forEach((citem, cindex) => {
          if (citem.checked) {
            if (this.checkedIds != '') {
              this.checkedIds = this.checkedIds + ',' + citem.nodeId;
            } else {
              this.checkedIds = this.checkedIds + citem.nodeId;
            }
          }
          citem.children.forEach((permItem, permIndex) => {
            if (permItem.checked) {
              if (this.checkedIds != '') {
                this.checkedIds = this.checkedIds + ',' + permItem.nodeId;
              } else {
                this.checkedIds = this.checkedIds + permItem.nodeId;
              }
            }
          });
        });
      });
      this.saveRolePermiss();
    },
    // 保存修改后的权限
    async saveRolePermiss () {
      const data = {
        roleId: this.roleId,
        ids: this.checkedIds
      };
      const resp = await saveRolePermiss(data);
      if (resp.data.msg == 'success') {
        this.getPermissByRoleId();
        this.$Message.success('保存成功');
      }
    },
    handleStaffSave () {
      this.getUserByRoleId();
    },
    // 点击全选
    handleCheckAll (e) {
      let self = this;
      // console.log(e,'是否选中')
      // self.checkAll = !self.checkAll;
      if (self.checkAll) {
        self.promisCheckList.forEach((item, index) => {
          item.checked = true;
          item.children.forEach((cItem, cIndex) => {
            cItem.checked = true;
            cItem.children.forEach((permItem, permIndex) => {
              permItem.checked = true;
            });
          });
        });
      } else {
        self.promisCheckList.forEach((item, index) => {
          item.checked = false;
          item.children.forEach((cItem, cIndex) => {
            cItem.checked = false;
            cItem.children.forEach((permItem, permIndex) => {
              permItem.checked = false;
            });
          });
        });
      }
    },
    // 父级菜单选择
    pCheckChange (e, pid) {
      // console.log(pid, e,'选择的父菜单的id', 111111);
      this.promisCheckList.forEach((item, index) => {
        if (item.nodeId == pid) {
          item.checked = e;
          var child = item.children;
          if (item.checked) {
            child.forEach((cItem, cIndex) => {
              cItem.checked = true;
              cItem.children.forEach((permItem, permIndex) => {
                permItem.checked = true;
              });
            });
          } else {
            child.forEach((cItem, cIndex) => {
              cItem.checked = false;
              cItem.children.forEach((permItem, permIndex) => {
                permItem.checked = false;
              });
            });
          }
        }
      });
      this.checkAllcheckbox();
    },
    // 子级菜单选择
    cCheckChange (e, cid, pindex) {
      // console.log(cid, '选择的子菜单的id', pindex, 111111);
      this.promisCheckList.forEach((item, index) => {
        if (pindex == index) {
          var isSelect = e;
          // console.log(isSelect);
          if (isSelect) {
            item.checked = true;
          }
          var child = item.children;
          child.forEach((cItem, cIndex) => {
            if (cItem.nodeId == cid) {
              cItem.checked = isSelect;
              cItem.children.forEach((permItem, permIndex) => {
                permItem.checked = isSelect;
              });
            }
          });
        }
      });
      this.checkoutChild();
      this.checkAllcheckbox();
    },
    // 权限选择
    permCheckChange (e, permid, pindex, cindex) {
      // console.log(cid, '选择的子菜单的id', pindex, 111111);
      this.promisCheckList.forEach((item, index) => {
        if (pindex == index) {
          var isSelect = e;
          // console.log(isSelect);
          if (isSelect) {
            item.checked = true;
          }
          var child = item.children;
          child.forEach((cItem, childIndex) => {
            if (cindex == childIndex) {
              cItem.checked = true;
              var perms = cItem.children;
              perms.forEach((permItem, permIndex) => {
                if (permItem.nodeId == permid) {
                  permItem.checked = isSelect;
                }
              });
            }
          });
        }
      });
      this.checkoutChild();
      this.checkAllcheckbox();
    },
    // 根据选择子菜单判断父菜单是否被选中
    checkoutChild () {
      this.promisCheckList.forEach((item, index) => {
        var child = item.children;
        var tag = false;

        child.forEach((cItem, cIndex) => {
          if (cItem.checked) {
            tag = true;
          }
        });
        if (tag) {
          item.checked = true;
        } else {
          item.checked = false;
        }
      });
    },
    // 判断当前全选是否被选中
    checkAllcheckbox () {
      var tag = true;
      this.promisCheckList.forEach((item, index) => {
        var child = item.children;
        if (!item.checked) {
          tag = false;
        }
        child.forEach((cItem, cIndex) => {
          if (!cItem.checked) {
            tag = false;
          }
        });
      });
      if (!tag) {
        this.checkAll = false;
      } else {
        this.checkAll = true;
      }
      // console.log(self.checkAll,'是否全选中')
    },
    checkFn (tagIndex, type) {
      console.log('type', type);
      console.log('this.type', this[type]);
      this[type].forEach((item, index) => {
        if (tagIndex === index) {
          item.isCheck = item.isCheck == true ? true : !item.isCheck;
          if (type == 'btns') {
            if (item.title == '添加角色') {
              this.addStatus = true;
            } else {
              this.addStatus = false;
            }
          } else if (type == 'promissionL') {
            if (item.title == '权限设置') {
              this.rightTab = 1;
              this.page = 1;
              this.getPermissByRoleId();
            } else {
              this.rightTab = 2;
              this.getUserByRoleId();
            }
          }

          //   item.isCheck = !item.isCheck; // 取反
        } else {
          item.isCheck = false;
        }
      });
    },
    // 编辑角色名称成功
    editNameBlur (id, name) {
      if (id) {
        this.pList.forEach((item, index) => {
          item.editStatus = false;
        });
        const data = {
          id: id,
          name: name
        };
        editRoleName(data)
          .then((res) => {
            if (res.data.msg == 'success') {
              this.getRoleList();
            }
          })
          .catch((err) => {
            console.log(err, '错误');
          });
      }
    },
    // 添加角色名称，失焦保存
    addBlur () {
      this.addStatus = false;
      if (this.roleName) {
        const data = {
          name: this.roleName
        };
        addRole(data)
          .then(res => {
            if (res.data.msg == 'success') {
              this.roleName = '';
              this.getRoleList();
            }
          })
          .catch(err => {
            console.log(err);
          });
      }
    },
    // 点击编辑角色名称
    editRoleName (id) {
      // console.log('点击事件1111', id);
      if (id) {
        this.pList.forEach((item, index) => {
          item.editStatus = false;
          if (item.id == id) {
            item.editStatus = true;
          }
        });
      }
    },
    // 删除角色
    delRoleName (id) {
      if (id) {
        this.$Modal.confirm({
          title: '确认删除？',
          content: '<p>数据删除后不可恢复，请确认是否删除数据？</p>',
          loading: true,
          onOk: () => {
            delRole(id)
              .then(res => {
                if (res.data.msg == 'success') {
                  this.$Modal.remove();
                  this.getRoleList();
                }
              })
              .catch(err => {
                console.log(err);
              });
          }
        });
      }
      // if (id) {

      //   delRole(id)
      //     .then(res => {
      //       if (res.data.msg == 'success') {
      //         self.getRoleList();
      //       }
      //     })
      //     .catch(err => {
      //       console.log(err);
      //     });
      // }
    },

    // 点击角色那一栏
    chooseRole (id) {
      if (id) {
        this.pList.forEach((item, index) => {
          if (item.id == id) {
            this.role = item.name + '(' + item.userCount + '人)';
            this.roleId = item.id;
          }
        });
        this.promissionL.forEach((item, index) => {
          item.isCheck = false;
        });
        this.promissionL[0].isCheck = true;
        this.rightTab = 1;
        this.getPermissByRoleId();
      }
    },

    // 编辑，查看角色所属人员
    handleRoleEditClick (id, type) {
      if (type == 'look') {
        this.modelTitle = '查看员工';
      } else if (type == 'edit') {
        this.modelTitle = '编辑员工';
      } else {
        this.modelTitle = '添加员工';
      }
      this.oprStaffId = id;
      this.modalStaffIsEdit = true;
      this.editStaffVisiable = true;
    },
    // 删除角色所属人员
    handleRoleDeleteClick (id) {
      this.$Modal.confirm({
        title: '确认删除？',
        content: '<p>数据删除后不可恢复，请确认是否删除数据？</p>',
        loading: true,
        onOk: async () => {
          await delUser({ userId: String(id) });
          this.getUserByRoleId();
          this.getRoleList('update');

          this.$Modal.remove();
        }
      });
    },

    // 分页部分
    handlePageChange (page) {
      this.page = page;
      this.getUserByRoleId();
    },
    handlePageSizeChange (pageSize) {
      this.pageSize = pageSize;
      this.getUserByRoleId();
    }
  }

};
</script>
<style lang="less">
.ivu-checkbox-group-item{
  display: block;
  margin: 5px 0px;
}
::-webkit-scrollbar {/*隐藏滚轮*/
  display: none;
}
.main .content-wrapper {
  margin:20px;
 }
.root {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  overflow: hidden;
  height: 100%;
  .left-part {
    width: 25%;
    height: 100%;
    padding: 0px 5px;
    overflow-y: auto;
    // background: pink;
    .role-title {
      width: 80%;
      // margin: 10px auto;
      margin-bottom:10px;
      display: flex;
      align-items: center;
      // justify-content: center;
      p {
        width: 50%;
        text-align: center;
        height: 40px;
        line-height: 40px;
        border-bottom: 1px solid #8f8f8f;
        color: #8f8f8f;
      }
      p:hover {
        cursor: pointer;
      }
      .p-checked {
        border-bottom: 2px solid #4319fc;
        color: #4319fc;
      }
      .p-notcheck {
        border-bottom: 1px solid #8f8f8f;
        color: #8f8f8f;
      }
    }
    .btn-group {
      width: 80%;
      // margin: 0 auto;
      display: flex;
      // justify-content: space-around;
    }
    .role-p {
      height: 30px;
      line-height: 30px;
      display: flex;
      input{
        height:30px;
      }
      p:nth-child(1),input{
          width: 70%;
      }
      p:nth-child(2){
          width: 30%;
          display: flex;
          justify-content: space-around;
          color: #4319fc;
      }
    }
    .role-p:hover {
      cursor: pointer;
      background: #e8eaec;
    }
  }
  .right-part {
    width: 80%;
    height: 100%;
    // background: goldenrod;
    border-left:1px solid #e8eaec;
    overflow-y:auto;
    position: relative;
    .role{
      margin-top: 20px;
      font-size: 16px;
      font-weight: bold;
    }
    .checkoutBox{
        display: block;
        min-height: 25px;
        line-height: 25px;
    }
    .perm-box{
      display: inline-block;
    }
    .child{
          margin-left:17px;
        }
    .cCheckItem{
      margin-left:20px;
    }
    .submit-btn {
      float: right;
      button {
        margin: 0 8px 20px;
      }
    }
    .pageBox{
      position: relative;
      clear: both;
      height: 50px;
      width: 100%;
      top: 30px;
    }
    .right-content {
      clear: both;
      width: 100%;
      padding: 20px;
      box-sizing: border-box;
      .promission-title {
        height: 100%;
        width: 20%;
        float: left;
        display: flex;
        align-items: center;
        justify-content: space-around;
        margin-bottom: 20px;
        p {
          width: 50%;
          text-align: center;
          height: 40px;
          line-height: 40px;
          border-bottom: 1px solid #8f8f8f;
          color: #8f8f8f;
        }
        p:hover {
          cursor: pointer;
        }
        .p-checked {
          border-bottom: 2px solid #4319fc;
          color: #4319fc;
        }
        .p-notcheck {
          border-bottom: 1px solid #8f8f8f;
          color: #8f8f8f;
        }
      }
    }
  }
}
</style>
